import axios from 'axios'
import { ElMessage } from 'element-plus' //element弹窗
import useUserStore from '@/store/modules/user' //用于获取全部路由信息  帮助递归展示多级路由菜单
const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000,
})

request.interceptors.request.use((request) => {
  const userStore = useUserStore()
  // console.log(request)
  if (userStore.token) request.headers.token = userStore.token //携带token发请求
  return request
})

request.interceptors.response.use(
  (response) => {
    // if (response.data.code == 200) {
    //   ElMessage({
    //     message: '登录成功',
    //     type: 'success',
    //   })
    // } else {
    //   ElMessage({
    //     message: '密码错误，登录失败',
    //     type: 'error',
    //   })
    // }
    return response.data
  },
  (error) => {
    //处理网络错误
    let msg = ''
    ElMessage({
      type: 'error',
      message: error + '',
    }) //element 报错提示
    const status = error.response.status
    switch (status) {
      case 401:
        msg = 'token过期'
        break
      case 403:
        msg = '无权访问'
        break
      case 404:
        msg = '请求地址错误'
        break
      case 500:
        msg = '服务器出现问题'
        break
      default:
        msg = '无网络'
    }

    return Promise.reject(error)
  },
)

export default request
